﻿using Microsoft.AspNetCore.Mvc;
using Adp.Core.Services;
using Adp.Core.Attribute;
using Adp;
using Adp.Models;
using Adp.Common;
using System;
using Microsoft.AspNetCore.Http;

namespace iTcm.Stage.Controllers
{
    public class MasterController : Controller
    {
        ManagerService managerService;
        MainService mainService;

        public MasterController(ManagerService managerService, MainService mainService)
        {
            this.managerService = managerService;
            this.mainService = mainService;
        }

        /// <summary>
        /// 后台主页
        /// </summary>
        /// <returns></returns>
        [HttpGet, AdminRoute("/")]
        public IActionResult Index()
        {
            mainService.HitStats(HitsStatus.成功);
            if (!managerService.Logged)
            {
                ViewBag.AnotherPlaceLogined = managerService.AnotherPlaceLogined;
                ViewBag.LoginUrl = Adp.Env.TcmBaseURL.Combine(Adp.Env.AdminPath, "login");
            }
            var LogonInfo = managerService.GetLogonInfo();
            return View(LogonInfo);
        }

        /// <summary>
        /// 后台登录口
        /// </summary>
        /// <returns></returns>
        [HttpGet, AdminRoute("/login")]
        public IActionResult Login()
        {
            mainService.HitStats(HitsStatus.成功);
            var LoginPage = Adp.Env.GetConfigurationValue("LoginPage");
            return View(LoginPage, new LogOn());
        }

        /// <summary>
        /// 后台登录口
        /// </summary>
        /// <returns></returns>
        [HttpPost, AdminRoute("/login")]
        public IActionResult Login(LogOn logOn)
        {
            var r = Adp.Env.GetRequestUrl();
            mainService.HitStats(HitsType.页面, r.Domain, "Post:" + r.Path, HitsStatus.成功);
            var LoginPage = Adp.Env.GetConfigurationValue("LoginPage");
            if (!ModelState.IsValid)
            {
                logOn.Succeed = false;
                return View(LoginPage, logOn);
            }
            //string Ip = Fn.GetIP();
            var loginErrS = Cookie.Get("loginErrS" + logOn.userid);
            if (loginErrS.HasValue())
            {
                ViewData["msg"] = "错误次数超过5次，账号锁定10分钟！";

                Adp.Logs.ManagerLogin.Login("管理员:{0} 错误次数超过5次，账号锁定10分钟！", logOn.userid);
                logOn.Succeed = false;
                return View(LoginPage, logOn);
            }
            var result = managerService.Login(logOn.userid, logOn.password);
            logOn.Succeed = result.Item1;
            //logOn.Succeed = managerService.Login(logOn.userid, logOn.password);
            if (!logOn.Succeed)
            {
                int error = 1;
                var ipError = Cookie.Get("loginErr" + logOn.userid);

                if (ipError.HasValue())
                {
                    error = Convert.ToInt32(ipError) + 1;
                    Cookie.Set("loginErr" + logOn.userid, error.ToString(), new CookieOptions
                    {
                        Expires = DateTime.Now.AddMinutes(10)
                    });
                }
                else
                {
                    Cookie.Set("loginErr" + logOn.userid, error.ToString(), new CookieOptions
                    {
                        Expires = DateTime.Now.AddMinutes(10)
                    });
                }
                if (error >= 5)
                {
                    Cookie.Set("loginErrS" + logOn.userid, error.ToString(), new CookieOptions
                    {
                        Expires = DateTime.Now.AddMinutes(10)
                    });
                }
                ViewData["msg"] = result.Item2;
                return View(LoginPage, logOn);
            }
            var rt = Adp.Common.Query.GetString();
            var url = Adp.Env.TcmBaseURL.Combine(Adp.Env.AdminPath);
            if (url == "")
            {
                url = "/";
            }

            if (rt.StartsWith("?rt="))
            {
                rt = System.Web.HttpUtility.UrlDecode(rt.Substring(4));
                if (rt.ToLower().StartsWith("http://") || rt.ToLower().StartsWith("https://"))
                {
                    url = System.Web.HttpUtility.UrlDecode(rt);
                }
                else
                {
                    url += "#" + rt.Substring(4);
                }
            }
            return new RedirectResult(url);
        }

        /// <summary>
        /// 站点访问
        /// </summary>
        /// <returns></returns>
        public ActionResult Site(string url)
        {
            if (T.Site != null)
            {
                mainService.HitStats(HitsStatus.成功);
                return View(T.templete + ".cshtml");
            }
            mainService.HitStats(HitsStatus.未找到);
            return new NotFoundResult();
        }

        [HttpGet, TcmRoute("/error")]
        public ActionResult Error()
        {
            return View();
        }

        [HttpGet, TcmRoute("/busy")]
        public ActionResult Busy()
        {
            return View(Env.VisitwaitView);
        }
    }
}